<template>
  <el-table
    ref="table"
    :data="tableData"
    v-bind="tableAttrs"
    :max-height="height"
    class="normal-table"
    v-on="tableListeners"
  >
    <template
      v-for="(head, index) in headers"
    >
      <el-table-column
        v-if="head.component"
        :key="index"
        v-bind="filterHead(head)"
      >
        <template
          #default="scope"
        >
          <component
            :is="head.component"
            :scope="scope.row"
            @onComponentChange="handleComponentChange"
          >
          </component>
        </template>
        <template
          #header="scope"
        >
          <component
            :is="head.head"
            v-if="head.head"
            v-bind="head"
          />
          <template
            v-else
          >
            {{ scope.column.label }}
          </template>
        </template>
      </el-table-column>
      <el-table-column
        v-else-if="head.slot"
        :key="index"
        :width="head.width"
        :label="head.label"
        :fixed="head.fixed"
      >
        <template
          #default="scope"
        >
          <slot
            :row="scope.row"
            :name="head.prop"
          >
          </slot>
        </template>
      </el-table-column>
      <el-table-column
        v-else
        :key="index"
        v-bind="head"
      >
      </el-table-column>
    </template>
  </el-table>
</template>

<script>
export default {
  name: 'NormalTable',
  props: {
    tableData: {
      type: Array,
      default () {
        return []
      }
    },
    tableAttrs: {
      type: Object,
      default () {
        return {}
      }
    },
    tableListeners: {
      type: Object,
      default () {
        return {}
      }
    },
    headers: {
      type: Array,
      default () {
        return []
      }
    },
    height: {
      type: Number,
      default: 0
    }
  },
  methods: {
    filterHead (head) {
      let map = {}
      for (let key in head) {
        if (key !== 'component' && key !== 'head') {
          map[key] = head[key]
        }
      }
      return map
    },
    handleComponentChange (payload) {
      this.$emit('onComponentChange', payload)
    }
  }
}
</script>

<style scoped lang="scss">
  .normal-table {
    height: 100%;

    /deep/.el-table__header {
      th {
        height: 39px !important;
        padding: 3px 0 !important;
        box-sizing: border-box !important;
      }
    }
  }
</style>
